# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time        : 2021/3/29 22:09
@Author      : Albert Darren
@Contact     : 2563491540@qq.com
@File        : SortMethod.py
@Version     : Version 1.0.0
@Description : TODO 实现插入排序，选择排序，合并排序
@Created By  : PyCharm
"""


def insert_sort(src, is_ascending=True):
    """
    对输入数据类型，如列表，字符串进行插入排序(属于原址排序)
    :param src:所有关键字类型相同，如全为数字的数据
    :param is_ascending:关键字排列顺序，默认从左到右从小到大，升序排列
    :return:指定排序后的对象
    """
    try:
        mutable = False
        hash(src)
        src = list(src)
    except TypeError:
        mutable = True
    finally:
        operator = ">" if is_ascending else "<"
        for j in range(1, len(src)):  # 取出第2个到最后一个元素
            key = src[j]
            i = j - 1
            while i >= 0 and eval("src[i] {} key".format(operator)):
                src[i + 1] = src[i]
                i -= 1
            src[i + 1] = key
    return src if mutable else "".join(src)


if __name__ == '__main__':
    ls = [4, 1, 5, 2, 3, 9, 7, 2]
    result_ls = insert_sort(ls)
    print(result_ls)
    string = "bcdfea"
    result_str = insert_sort(string, False)
    print(result_str)
